<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>聊天室{{ room_name }}</title>
</head>
<body>
    <textarea id="chat-log" cols="100" rows="20"></textarea>
    <br/>
    <input id="input" type="text" size="100"/><br/>
    <input id="submit" type="button" value="发 送"/>
</body>
<script>
    var roomName = '{{ room_name }}';

    var chatSocket = new WebSocket(
        'ws://' + window.location.host +
        '/ws/chat/' + roomName + '/');

    chatSocket.onmessage = function(e) {
        var data = JSON.parse(e.data);
        var message = data['message'];
        document.querySelector('#chat-log').value += (message + '\n');
    };

    chatSocket.onclose = function(e) {
        console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#input').focus();
    document.querySelector('#input').onkeyup = function(e) {
        if (e.keyCode === 13) {  // enter, return
            document.querySelector('#submit').click();
        }
    };

    document.querySelector('#submit').onclick = function(e) {
        var messageInputDom = document.querySelector('#input');
        var message = messageInputDom.value;
        chatSocket.send(JSON.stringify({
            'message': message
        }));

        messageInputDom.value = '';
    };
</script>
</html>